﻿namespace Minesweeper
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    static class MineFieldExtensions
    {
        public static void PlaceMines(this MineField mineField)
        {
            int rows = mineField.Height;
            int cols = mineField.Width;
            int numberOfMines = mineField.NumberOfMines;

            while (numberOfMines > 0)
            {
                int randomRow = MinesweeperGame.RandomGenerator.Next(0, rows);
                int randomCol = MinesweeperGame.RandomGenerator.Next(0, cols);
                if (!mineField[randomRow, randomCol].IsMine && mineField[randomRow, randomCol] != mineField.CurrentCell)
                {
                    mineField[randomRow, randomCol].MakeMine();
                    numberOfMines--;
                }
            }
        }

        public static void FillGameBoard(this MineField mineField)
        {
            for (int row = 0; row < mineField.Height; row++)
            {
                for (int col = 0; col < mineField.Width; col++)
                {
                    if (!mineField[row, col].IsMine)
                    {
                        mineField[row, col].Content = GetNeighborMinesCount(mineField, row, col);
                    }
                    else
                    {
                        mineField[row, col].Content = -1;
                    }
                }
            }
        }

        private static int GetNeighborMinesCount(MineField mineField, int row, int col)
        {
            int count = 0;

            count += ProcessNeighborCell(mineField, row - 1, col - 1);
            count += ProcessNeighborCell(mineField, row - 1, col);
            count += ProcessNeighborCell(mineField, row - 1, col + 1);
            count += ProcessNeighborCell(mineField, row, col - 1);
            count += ProcessNeighborCell(mineField, row, col + 1);
            count += ProcessNeighborCell(mineField, row + 1, col - 1);
            count += ProcessNeighborCell(mineField, row + 1, col);
            count += ProcessNeighborCell(mineField, row + 1, col + 1);

            return count;
        }

        private static int ProcessNeighborCell(MineField mineField, int row, int col)
        {
            if (IsInMatrix(mineField, row, col))
            {
                if (mineField[row, col].IsMine)
                {
                    return 1;
                }
            }

            return 0;
        }

        public static bool IsInMatrix(this MineField mineField, int row, int col)
        {
            return row >= 0 && row < mineField.Height && col >= 0 && col < mineField.Width;
        }
    }
}
